package com.contact;

import java.io.File;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import com.android.ocean.util.common.BitmapUtil;
import com.android.ocean.util.common.StringUtil;
import com.app.DemoApplication;
import com.common.method.ServerPath;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.util.PathUtil;
import com.google.android.imageloader.ImageLoader;
import com.http.UploadFileTask;
import com.http.UserInfoModifyTask;
import com.http.UserInfoTask;
import com.matang.R;
import com.modle.User;
import com.util.AppUtil;
import com.util.UserUtil;

public class UserBaseInfoActivity extends AbstractPhotoActivity implements
		OnClickListener, UploadFileTask.CallBack, UserInfoModifyTask.CallBack ,	UserInfoTask.CallBack{
	LinearLayout photoCon, localImgCon;
	ImageView thumbIv;
	EditText nameEt, nickNameEt;
	RadioButton rdMale, rdFemale;
	User user;
	public static final int REQUEST_CODE_CAMERA = 18;
	private File cameraFile;
	String tmpPhotoPath=null;//临时保存图片的本地路径
	String name=null;
	String nickName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_user_baseinfo);

		init();
	}

	void init() {
		mContext = UserBaseInfoActivity.this;
		findViews();
		initPaneData();
	}
	
	private void loadUserData() {
		showProgressDialog();
		new UserInfoTask(this).execute(user.id);
	}

	
	/**
	 * 照相获取图片
	 */
	public void selectPicFromCamera() {
		if (!CommonUtils.isExitsSdcard()) {
			Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照", 0).show();
			return;
		}

		cameraFile = new File(PathUtil.getInstance().getImagePath(), DemoApplication.getInstance().getUserName()
				+ System.currentTimeMillis() + ".jpg");
		cameraFile.getParentFile().mkdirs();
		startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
				REQUEST_CODE_CAMERA);
	}
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
			super.onActivityResult(requestCode, resultCode, data);
			 if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
					if (cameraFile != null && cameraFile.exists()){
						
					}
			 }
		}

	public void initPaneData() {
		super.initPaneData();
		user = UserUtil.readUser();
		loadUserData();
		header.headTitleTv.setText("添加资料");
		header.headLeftTv.setText("取消");
		header.headRightTv.setText("完成");
		header.headRightTv.setVisibility(View.VISIBLE);
		photoCon.setOnClickListener(this);
		localImgCon.setOnClickListener(this);
		header.headRightTv.setOnClickListener(this);
		header.headLeftTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				finish();
				
			}
		});

		flshUser();
	}
	private void flshUser(){

		/***** 初始化用户信息 ******/
		if (user != null) {
			ImageLoader.get(mContext).bind(thumbIv,ServerPath.SERVER+user.thumb, null,R.drawable.default_head);

			nickNameEt.setText(user.nickName);
			String name = user._user_resume;
			String userName = "";
			if (name != null) {
				try {
					userName = new JSONObject(name).getString("name");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			nameEt.setText(userName);
			if("m".equalsIgnoreCase(user.male)){
				rdMale.setChecked(true);
			}else{
				rdFemale.setChecked(true);
			}
		}
	}
	
	
	public void procUserInfoData(User data) {
		dismissProgressDialog();
		user = data;
		flshUser();

	}


	public void procUserInfoError(String msg) {
		AppUtil.tsMsg(mContext, "获取用户信息失败：" + msg);

		finish();
	}


	@Override
	protected void findViews() {
		super.findViews();
		photoCon = (LinearLayout) findViewById(R.id.photo_con);
		localImgCon = (LinearLayout) findViewById(R.id.local_img_con);
		thumbIv = (ImageView) findViewById(R.id.thumb_iv);
		rdMale = (RadioButton) findViewById(R.id.rd_male);
		rdFemale = (RadioButton) findViewById(R.id.rd_fmale);
		nameEt = (EditText) findViewById(R.id.name_et);
		nickNameEt = (EditText) findViewById(R.id.nickname_et);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.photo_con:
			takePhoto();
			break;
		case R.id.local_img_con:
			pickPhoto();
			break;
		case R.id.headRight:
			submit();
			break;
		}
	}

	
	/**
	 * 
	 * @Description:TODO
	 * @param@return
	 * @return String
	 * @author zhuw
	 * @date 2013-8-20 上午10:32:49
	 */
	private String check(){
		StringBuffer result=new StringBuffer();
		name=nameEt.getText().toString();
		nickName=nickNameEt.getText().toString();
		if(StringUtil.isNull(name)){
			result.append("用户名不能为空");
		}
		if(StringUtil.isNull(nickName)){
			result.append("昵称不能为空");
		}
		return result.toString();
	}
	private void submit() {
		
		String checkRes=check();
		if(StringUtil.isNull(checkRes)){
			if(StringUtil.isNull(tmpPhotoPath)){
				//没有图片则直接更新信息
				submitUserInfo(null);
			}else{
				//有图片先上传图片,获取路径后再修改用户信息
				uploadFile(tmpPhotoPath);
			}
			
		}else{
			AppUtil.tsMsg(mContext, checkRes);
		}
	}
	/**
	 * 
	 * @Description:TODO更新用户信息
	 * @param@param headPath
	 * @return void
	 * @author zhuw
	 * @date 2013-8-20 上午10:43:42
	 */
	private void submitUserInfo(String headPath) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("id", user.id);
		map.put("name", name);
		map.put("nickname", nickName);
		if (rdMale.isChecked()) {
			map.put("sex", "m");
		} else {
			map.put("sex", "f");
		}
		if(!StringUtil.isNull(headPath)){
			map.put("avatar", headPath);
		}
		showProgressDialog("用户信息更新中...");
		new UserInfoModifyTask(this).execute(map);
		
	}

	
	
	@Override
	public void procError(String msg) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, msg);

	}

	@Override
	public void procUploadFile(String result) {
		dismissProgressDialog();
		try {
			JSONObject jo = new JSONObject(result);
			String thumb = jo.optString("thumbnail_src");
			if(!StringUtil.isNull(thumb)){
				submitUserInfo(thumb);
			}else{
				submitUserInfo(jo.optString("src"));
			}
			
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		
		

	}
	@Override
	public void procUploadFileError(String result) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, "文件上传失败");
		
	}
	@Override
	protected void donePhoto(String photoPath) {
		tmpPhotoPath=photoPath;
		Bitmap bit = BitmapUtil.getImageThumbnail(photoPath, 100, 100);
		if (bit != null) {
			thumbIv.setImageBitmap(bit);
		}
	}
	  /**
     * 
     * @Description:TODO上传文件
     * @param@param fullPathName
     * @return void
     * @author zhuw
     * @date 2013-8-17 下午1:10:38
     */
	void uploadFile(String fullPathName) {
		showProgressDialog("头像上传中...");

//		new UploadFileTask(this).execute(
//				Environment.getExternalStorageDirectory()+File.separator,
//				"1.png");
		new UploadFileTask(this).execute(
				StringUtil.getLocalFilePath(fullPathName),
				StringUtil.getLocalFileName(fullPathName));

	}
	@Override
	public void procUserInfoModify(User data) {
		dismissProgressDialog();
		UserUtil.saveUser(data);
		DemoApplication.getInstance().handler.sendEmptyMessage(1);
		finish();
		
	}
}
